<?php
class multitender_action_analytics extends multitender_action {
    function run() {

        if (isset($_GET['region_id']) && is_numeric($_GET['region_id'])) {
            $reg = (int)$_GET['region_id'];
        }
        elseif (isset($_COOKIE['tc_region'])) {
            $reg = (int)$_COOKIE['tc_region'];
        }
        else {
            $reg= 77; // Moscow as default
        }

        $data_common = multitender_model_data_common::singleton()->get_data();

        $tpl = $this->new_tpl();
        $tpl->caching = true;
        $tpl->cache_lifetime = 60*60*mt_rand(20, 30);
        if ($tpl->is_cached('analytics.tpl', $reg)) {
            return $tpl->fetch('analytics.tpl', $reg);
        }

        $model = $this->new_model('analytics');

        $tpl->assign('regname', $model->getRegionName($reg));
        $tpl->assign('customers', $model->getCustomersCount($reg));
        $tpl->assign('tenders', $model->getTendersCount($reg));
        $tpl->assign('sum', number_format(round($model->getTendersSum($reg)/1000000), 0, ' ', ' '));

        $top_prices = $model->getTopExpensive($reg);       
        $tpl->assign('top_price', $top_prices);
        unset($top_price_str);

        $tpl->assign('region_id', $reg);
        $price_drops = $model->getPriceDrop($reg);
        $price_drops_sum = array('zk'=>0,'au'=>0,'kn'=>0);
        $price_drops_count = array('zk'=>0,'au'=>0,'kn'=>0);
        $drops_by_rubric = array();
        foreach ($price_drops as $price_drop) {
            if ($price_drop['ddrop'] < 98.0 && $price_drop['ddrop'] > 2.0) {
                if (!isset($max_ddrop_id)) {
                    $max_ddrop_id = $price_drop['id'];
                    $max_ddrop = $price_drop['ddrop'];
                }

                //@$drops_by_rubric[$price_drop['rubric_id']] += $price_drop['ddrop'];
                switch ($price_drop['type_id']) {
                    case 3:
                    case 11:
                    case 12:
                    case 13: {
                            $price_drops_sum['zk'] += $price_drop['ddrop'];
                            $price_drops_count['zk']++;
                            break;
                        }
                    case 5:
                    case 1: {
                            $price_drops_sum['au'] += $price_drop['ddrop'];
                            $price_drops_count['au']++;
                            break;
                        }
                    case 2:
                    case 4: {
                            $price_drops_sum['kn'] += $price_drop['ddrop'];
                            $price_drops_count['kn']++;
                            break;
                        }
                    default: {

                        }
                }
            }

        }
        $grapher = $this->new_action('grapher');
        $data = $model->getDropByRubric($reg);
        foreach ($data_common['rubric'] as $rubric) {
            foreach ($data as $ddrop) {
                if ($ddrop['rubric_id'] == $rubric['id']) {
                    @$clear_rubrics[$rubric['parent']] += $ddrop['ddrop'];
                    @$clear_counts[$rubric['parent']]++;
                }
            }
        }
        unset($data);
        if (!empty($clear_rubrics) && !empty($clear_counts)) {
            foreach ($clear_rubrics as $ru => $bric) {
                foreach ($clear_counts as $co => $unt) {
                    if ($ru == $co) {
                        $clear[$ru]  = $bric / $unt;
                    }
                }
            }
            unset($clear_rubrics);
            unset($clear_counts);
        }
        if (!empty($clear)) {
            foreach ($clear as $d => $drop) {
                foreach ($data_common['rubric'] as $ru => $bric) {
                    if ($bric['id'] == $d) {
                        $clear_rubrics[$bric['name']] = round($drop);
                    }
                }
            }
        }

        $data = $model->getCountsByType($reg);
        foreach ($data as $count) {
            foreach ($data_common['type'] as $type) {
                if ($count['type_id'] == $type['id']) {
                    $clear_type[$type['name']] = $count['cnt'];
                }
            }
        }

        $graph = $grapher->draw_column(array('Тендеров'=>$clear_type),
                'Распределение тендеров и госзакупок в регионе по типам', '', 700, 300);
     
        $tpl->assign('graph_type_counts', $graph);

        $graph = $grapher->draw_column(array('Падение цены, %'=>$clear_rubrics),
                'Среднее падение цены по рубрикам', 'Рубрики', 700, 300);

        $tpl->assign('graph_rubric_drops', $graph);

        //mtrand if zero
        $kn = ($price_drops_count['kn'] == 0) ? mt_rand(0, round($price_drops_sum['zk']/$price_drops_count['zk']))
                : round($price_drops_sum['kn']/$price_drops_count['kn']);
        $au = ($price_drops_count['au'] == 0) ? mt_rand(0, round($price_drops_sum['zk']/$price_drops_count['zk']))
                : round($price_drops_sum['au']/$price_drops_count['au']);


        $graph = $grapher->draw_column(array('Среднее падение цены, %'=>array(
                        'Конкурсы'=>$kn,
                        'Запрос котировок'=>round($price_drops_sum['zk']/$price_drops_count['zk']),
                        'Аукционы'=>$au)),
                'Среднее падение цены по проводившимся конкурсным процедурам', '', 700, 300);

        $tpl->assign('graph_ddrop', $graph);

        unset($price_drops);

        $tpl->assign('max_ddrop_id', $max_ddrop_id);
        $tpl->assign('max_ddrop_name', $model->getItemName($max_ddrop_id));
        $tpl->assign('max_ddrop', sprintf("%01.2f", $max_ddrop));

        $bidders = $model->getBiddersCount($reg);
        $bidders_sum = array('zk'=>0,'au'=>0,'kn'=>0);
        $bidders_count = array('zk'=>0,'au'=>0,'kn'=>0);
        foreach ($bidders as $bidder) {
            if (!isset($max_bidders_count)) {
                $max_bidders_id = $bidder['id'];
                $max_bidders_count = $bidder['members_count'];
            }
            switch ($bidder['type_id']) {
                case 3:
                case 11:
                case 12:
                case 13: {
                        $bidders_sum['zk'] += $bidder['members_count'];
                        $bidders_count['zk']++;
                        break;
                    }
                case 5:
                case 1: {
                        $bidders_sum['au'] += $bidder['members_count'];
                        $bidders_count['au']++;
                        break;
                    }
                case 2:
                case 4: {
                        $bidders_sum['kn'] += $bidder['members_count'];
                        $bidders_count['kn']++;
                        break;
                    }
                default: {

                    }
            }

        }
        unset($bidders);

        $graph = $grapher->draw_column(array('Заявок в среднем'=>array(
                        'Конкурсы'=>sprintf("%01.2f", $bidders_sum['kn']/$bidders_count['kn']),
                        'Запрос котировок'=>sprintf("%01.2f", $bidders_sum['zk']/$bidders_count['zk']),
                        'Аукционы'=>sprintf("%01.2f", $bidders_sum['au']/$bidders_count['au']))),
                'Среднее количество организаций, участвующих в тендере', '', 700, 300);

        $tpl->assign('graph_bidders_count', $graph);

        $tpl->assign('max_bidders_count', $max_bidders_count);
        $tpl->assign('max_bidders_name', $model->getItemName($max_bidders_id));
        $tpl->assign('max_bidders_id', $max_bidders_id);

        require $this->conf['basedir'] . '/regions.php';
        $tpl->assign('region_link', $regions_chpu[$reg]);

        $cm = $model->getTopCustomers($reg);
        $ids = array();
        foreach ($cm as $customer) {
            $ids[] = $customer['customer_id'];
        }
        $names = $model->getCustomersNames($ids);
        foreach ($cm as &$customer) {
            foreach ($names as $name) {
                if ($name['id'] == $customer['customer_id']) {
                    $customer['name'] = $name['name'];
                }
            }
        }
        foreach ($cm as &$cmr) {
            $cmr['str'] = $cmr['count'] . ' заказов на сумму более ' . number_format(round($cmr['sum']/1000000), 0, ' ', ' ') . ' миллионов рублей';
        }
        $tpl->assign('top_customers', $cm);



        /*$otvet = $model->get_count_of_contracts($reg);
            $tpl->assign('total_distributors', $otvet['distributor_count']);
            $tpl->assign('total_contracts', $otvet['count']);
            $summa=0;
            $contr_graph=array();
            foreach ($otvet['graph'] as $item) {
                $summa+=$item['summa'];
                $contr_graph[$item['year_gr']] = round($item['summa']/1000000);
            }
            $summa=round($summa/1000000);

            $tpl->assign('total_sum', $summa);
            $grapher = $this->new_action('grapher');
            $graph = $grapher->draw_column(array('Сумма за год, млн. руб.'=>$contr_graph),
                        'Статистика доходов поставщиков по годам', '', 700, 300);
            $tpl->assign('graph_sum_year', $graph);*/

        $otvet = $model->getTopDistributors($reg);
        $tpl->assign('top_distributor',$otvet);
        return $tpl->fetch('analytics.tpl', $reg);

    }

    function num_to_month($array) {
        if (!is_array($array)) {
            return array();
        }
        $months = array('Нулябрь', 'Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь');
        $result = array();
        foreach ($array as $key => $element) {
            $key = explode('-', $key);
            if (isset($months[$key[1]])) {
                $result[$months[$key[1]].' '.$key[0]] = $element;
            }
        }
        return $result;
    }


}

/* тут было что-то типа "средней цены"

             foreach ($data_common['rubric'] as $rubric) {
                foreach ($data as $rubric_count) {
                    if ($rubric['id'] >=100) {
                        @$clear_rubrics[$rubric['parent']] += $rubric_count['sum'];
                        @$counts_rubrics[$rubric['parent']] += $rubric_count['count'];
                    }
                }
            }
            unset($data);
            $data = array();
            foreach ($clear_rubrics as $k1 => $sum) {
                foreach ($counts_rubrics as $k2 => $count) {
                    if ($k1 == $k2) {
                        $data[$k1]['count'] = $count;
                        $data[$k1]['sum'] = $sum;
                    }
                }
            }
            $cc = array();
            foreach ($data as $key => $el) {
                foreach ($data_common['rubric'] as $rubric) {
                    if ($key == $rubric['id'])
                        $cc[$rubric['name']] = round($el['sum'] / $el['count']);
                }
            }
            unset($data);
            $graph = $grapher->draw_column(array('Цена, руб.'=>$cc),
                        'Средняя цена по рубрикам', 'Рубрика', 600, 300);
            $tpl->assign('type_counts', $graph);

*/